﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Controller;
using BusinessModel;
using ManageStore.Config;
using Controller.DataProvider;
using BaseUtilities;
using ManageStore.IViews;
using System.Collections;

namespace ManageStore.Forms
{
    public partial class FrmProduct : BaseForm, IProductView
    {
        public FrmProduct()
        {
            InitializeComponent();
            _ProductCtr = new ProductCtr(this);
            productCtrBindingSource.DataSource = ProductCtr;
            BindData();
            EvtNew += ProductCtr.MtdNew;
            EvtEdit += ProductCtr.MtdEdit;
            EvtDelete += ProductCtr.MtdDelete;
            EvtSave += ProductCtr.MtdSave;
            EvtGetAllChilds += ProductCtr.MtdGetAllChilds;
            EvtGetAllByTypeId += ProductCtr.MtdGetAllByTypeId;
            EvtReloadLstProductType += ProductCtr.MtdReloadLstProductType;
            EvtReloadLstUnit += ProductCtr.MtdReloadLstUnit;
        }
        private void FrmProduct_Load(object sender, EventArgs e)
        {
            dgvProduct.AutoGenerateColumns = false;
            CreateTreeview();
            cbbProductType.SelectedIndex = -1;
        }

        private bool IsLoaded;
        #region Properties
        // ProductCtr.
        private ProductCtr _ProductCtr;
        public ProductCtr ProductCtr
        {
            get { return _ProductCtr; }
            set { _ProductCtr = value; }
        }
        //----------------------------------------
        public event EventHandler EvtSaved;
        public bool IsDialog { get; set; }
        public string ProductCode
        {
            get { return txtCode.Text; }
            set { txtCode.Text = value; }
        }
        public string ProductName
        {
            get { return txtName.Text; }
            set { txtName.Text = value; }
        }
        #endregion Properties

        #region Private Methods
        //----------------------------------------
        private void BindData()
        {
            dgvProduct.DataSource = ProductCtr.LstProduct;
            cbbProductType.DataSource = ProductCtr.LstProductType;
            cbbUnit.DataSource = ProductCtr.LstUnit;
        }
        //----------------------------------------
        private void CreateTreeview()
        {
            TreeNode oTreeNode = new TreeNode();
            oTreeNode.Name = "0";
            oTreeNode.Text = "Gốc";
            trvParentType.Nodes.Clear();
            trvParentType.Nodes.Add(oTreeNode);
            OnGetAllChilds((result) =>
            {
                IList<ProductType> lstPro = result as IList<ProductType>;
                CreateSubNode(oTreeNode, lstPro);
                trvParentType.SelectedNode = oTreeNode;
                oTreeNode.Expand();
            });
        }
        //----------------------------------------
        private void CreateSubNode(TreeNode pTreeNode, IList<ProductType> pLstProductType)
        {
            pLstProductType.ToList().ForEach((item) =>
            {
                TreeNode oTreeNode = new TreeNode();
                oTreeNode.Name = item.Id.ToString();
                oTreeNode.Text = item.Name;
                pTreeNode.Nodes.Add(oTreeNode);
                OnGetAllChilds((childs) =>
                {
                    IList<ProductType> lstPro = childs as IList<ProductType>;
                    CreateSubNode(oTreeNode, lstPro);
                }, item.Id);
                //IList<ProductType> lstPro = _ProductTypeCtr.GetAllChilds(item.Id).ToResult<IList<ProductType>>();
            });
        }
        //----------------------------------------
        private bool CheckValidate()
        {
            bool result = false;
            errorProvider1.Clear();
            IList<IdNameModel> lstUnit = cbbUnit.DataSource as IList<IdNameModel>;
            if (lstUnit == null || lstUnit.Count == 0)
            {
                if (MessageBox.Show("Chưa có đơn vị tính", "Lỗi", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.OK)
                {
                    FrmUnit oFrmUnit = new FrmUnit();
                    oFrmUnit.ShowDialog();
                    OnReloadLstUnit();
                }
                lstUnit = cbbUnit.DataSource as IList<IdNameModel>;
                //result = cbbUnit.SelectedIndex < 0;
            }
            if (cbbUnit.SelectedValue == null)
            {
                errorProvider1.SetError(cbbUnit, "Không thể rỗng");
                result = true;
            }
            if (cbbProductType.SelectedValue == null)
            {
                errorProvider1.SetError(cbbProductType, "Không thể rỗng");
                result = true;
            }
            if (string.IsNullOrWhiteSpace(txtCode.Text))
            {
                errorProvider1.SetError(txtCode, "Không thể rỗng");
                result = true;
            }
            if (string.IsNullOrWhiteSpace(txtName.Text))
            {
                errorProvider1.SetError(txtName, "Không thể rỗng");
                result = true;
            }
            return result;
        }
        #endregion Private Methods

        #region IProductView Members
        //----------------------------------------
        public event ActionInvoke EvtGetAllChilds;
        public void OnGetAllChilds(Action<object> pAction, params object[] pParams)
        {
            if (EvtGetAllChilds != null)
                EvtGetAllChilds(pAction, pParams);
        }
        //----------------------------------------
        public event MethodInvoke EvtGetAllByTypeId;
        public void OnGetAllByTypeId(params object[] pParams)
        {
            if (EvtGetAllByTypeId != null)
                EvtGetAllByTypeId(pParams);
        }
        //----------------------------------------
        public event MethodInvoke EvtReloadLstProductType;
        public void OnReloadLstProductType(params object[] pParams)
        {
            if (EvtReloadLstProductType != null)
                EvtReloadLstProductType(pParams);
        }
        //----------------------------------------
        public event MethodInvoke EvtReloadLstUnit;
        public void OnReloadLstUnit(params object[] pParams)
        {
            if (EvtReloadLstUnit != null)
                EvtReloadLstUnit(pParams);
        }
        //----------------------------------------
        public void ReloadData(params string[] pParams)
        {
            foreach (string item in pParams)
            {
                switch (item)
                {
                    case "LstProductType":
                        cbbProductType.DataSource = ProductCtr.LstProductType;
                        break;
                    case "LstUnit":
                        cbbUnit.DataSource = ProductCtr.LstUnit;
                        break;
                    case "LstProduct":
                        IsLoaded = false;
                        dgvProduct.DataSource = ProductCtr.LstProduct;
                        break;
                }
            }
        }

        // Before.
        //----------------------------------------
        public override bool BeforeHandler(string pEventName, params object[] pParams)
        {
            bool result = true;
            switch (pEventName)
            {
                case "EvtNew":
                    dgvProduct.ClearSelection();
                    errorProvider1.Clear();
                    break;
                case "EvtEdit":
                    break;
                case "EvtDelete":
                    int iProductId = 0;
                    int.TryParse(lblProductId.Text, out iProductId);
                    if (iProductId > 0)
                    {
                        result = MessageBox.Show("Bạn có chắc muốn xóa không?", "Cảnh báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK;
                    }
                    break;
                case "EvtSave":
                    result = !CheckValidate();
                    break;
            }
            return result;
        }
        // Error.
        //----------------------------------------
        public override bool ErrorHandler(string pEventName, params object[] pParams)
        {
            bool result = true;
            switch (pEventName)
            {
                case "EvtDelete":
                    if (pParams.Count() == 1)
                    {
                        ResultModel oResultModel = pParams[0] as ResultModel;
                        if (oResultModel.ErrorNumber == ManageStoreConfig.ErrorForeignKey)
                        {
                            MessageBox.Show("Hàng này đã được dùng. Không thể xóa được!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    break;
                case "EvtSave":
                    string sError = "Không thể lưu được.";
                    if (pParams.Count() == 1)
                    {
                        Dictionary<string, string> lstError = pParams[0] as Dictionary<string, string>;
                        if (lstError != null && lstError.Count > 0)
                        {
                            if (lstError.Keys.Contains("UnitId") && (cbbUnit.DataSource as IList).Count == 0)
                            {
                                if (MessageBox.Show("Chưa có đơn vị tính", "Lỗi", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.OK)
                                {
                                    int iProductTypeId = default(int);
                                    FrmUnit oFrmUnit = new FrmUnit();
                                    oFrmUnit.EvtSaved += (sen, ea) =>
                                    {
                                        int.TryParse(sen.ToString(), out iProductTypeId);
                                    };
                                    oFrmUnit.Activated += (senl, eal) =>
                                    {
                                        oFrmUnit.UnitName = cbbUnit.Text;
                                    };
                                    oFrmUnit.IsDialog = true;
                                    oFrmUnit.ShowDialog();
                                    if (iProductTypeId != default(int))
                                    {
                                        OnReloadLstUnit();
                                        if (cbbUnit.SelectedValue != null)
                                        {
                                            return true;
                                        }
                                    }
                                }
                            }
                            if (lstError.Keys.Contains("ProductTypeId") && (cbbProductType.DataSource as IList).Count == 0)
                            {
                                if (MessageBox.Show("Chưa có loại hàng hóa", "Lỗi", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.OK)
                                {
                                    int iProductTypeId = default(int);
                                    FrmProductType oFrmProductType = new FrmProductType();
                                    oFrmProductType.EvtSaved += (sen, ea) =>
                                    {
                                        int.TryParse(sen.ToString(), out iProductTypeId);
                                    };
                                    oFrmProductType.Activated += (senl, eal) =>
                                    {
                                        oFrmProductType.ProductTypeName = cbbProductType.Text;
                                    };
                                    oFrmProductType.IsDialog = true;
                                    oFrmProductType.ShowDialog();
                                    if (iProductTypeId != default(int))
                                    {
                                        CreateTreeview();
                                        OnReloadLstProductType();
                                        if (cbbProductType.SelectedValue != null)
                                        {
                                            return true;
                                        }
                                    }
                                }
                            }
                            sError = "Dữ liệu nhập vào không hợp lệ.";
                        }
                    }
                    MessageBox.Show(sError, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
            }
            return result;
        }
        // Completed.
        //----------------------------------------
        public override bool CompletedHandler(string pEventName, params object[] pParams)
        {
            bool result = true;
            switch (pEventName)
            {
                case "EvtNew":
                    cbbProductType.Focus();
                    break;
                case "EvtEdit":
                    cbbProductType.Focus();
                    errorProvider1.Clear();
                    break;
                case "EvtSave":
                    int iProductId = 0;
                    int.TryParse(pParams[0].ToString(), out iProductId);
                    if (EvtSaved != null)
                    {
                        EvtSaved(iProductId, null);
                        if (IsDialog)
                            this.Close();
                    }
                    OnEvtNew();
                    break;
                case "EvtDelete":
                    OnEvtNew();
                    break;
            }
            return result;
        }
        // Validation.
        //----------------------------------------
        public override bool ValidationHandler(string pColumnName, params object[] pParams)
        {
            bool result = true;
            if (!string.IsNullOrWhiteSpace(pColumnName))
            {
                // Get Error control.
                Control ctl = null;
                switch (pColumnName)
                {
                    case "ProductTypeId":
                        ctl = cbbProductType;
                        break;
                    case "ProductCode":
                        ctl = txtCode;
                        break;
                    case "ProductName":
                        ctl = txtName;
                        break;
                    case "UnitId":
                        ctl = cbbUnit;
                        break;
                }
                // Set Control Error.
                if (ctl != null)
                {
                    if (pParams.Count() == 1 && !string.IsNullOrEmpty(pParams[0].ToString()))
                        errorProvider1.SetError(ctl, pParams[0].ToString());
                    else
                        errorProvider1.SetError(ctl, null);
                }
            }
            return result;
        }
        #endregion

        #region Dotnet Methods
        //----------------------------------------
        private void btnAdd_Click(object sender, EventArgs e)
        {
            OnEvtNew();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            OnEvtSave();
        }
        //----------------------------------------
        private void btnDelete_Click(object sender, EventArgs e)
        {
            OnEvtDelete();
        }
        //----------------------------------------
        private void btnQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //----------------------------------------
        private void dgvProduct_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            dgvProduct.ClearSelection();
            IsLoaded = true;
        }
        //----------------------------------------
        private void dgvProduct_SelectionChanged(object sender, EventArgs e)
        {
            if (IsLoaded && dgvProduct.SelectedRows.Count > 0)
            {
                OnEvtEdit(dgvProduct.SelectedRows[0].DataBoundItem);
            }
        }
        //----------------------------------------
        private void cbbProductType_SelectedIndexChanged(object sender, EventArgs e)
        {
        }
        //----------------------------------------
        private void cbbProductType_SelectedValueChanged(object sender, EventArgs e)
        {
            ComboBox cbb = sender as ComboBox;
            if (IsLoaded && cbb.SelectedValue != null)
            {
                TreeNode oTreeNode = trvParentType.Nodes.Find(cbb.SelectedValue.ToString(), true).FirstOrDefault();
                trvParentType.CollapseAll();
                oTreeNode.Parent.Expand();
                trvParentType.SelectedNode = oTreeNode;
                OnGetAllByTypeId(cbb.SelectedValue);
            }
        }
        //----------------------------------------
        private void trvParentType_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Nodes.Count == 0)
            {
                cbbProductType.SelectedValue = int.Parse(e.Node.Name);
            }
        }
        //----------------------------------------
        private void lblProductId_TextChanged(object sender, EventArgs e)
        {
            btnDelete.Enabled = !string.IsNullOrWhiteSpace(lblProductId.Text) && Convert.ToInt32(lblProductId.Text) > 0;
        }
        //----------------------------------------
        private void FrmProduct_Activated(object sender, EventArgs e)
        {
            if (!IsLoaded)
            {
                IsLoaded = true;
            }
        }
        //----------------------------------------
        private void cbbProductType_Validated(object sender, EventArgs e)
        {
            if (!this.Disposing && cbbProductType.SelectedValue == null && !string.IsNullOrWhiteSpace(cbbProductType.Text))
            {
                //_BuyProductCtr.BuyOrderDetail.ProductId = default(int);
                if (MessageBox.Show("Chưa có loại hàng hóa", "Lỗi", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.OK)
                {
                    int iProductTypeId = default(int);
                    FrmProductType oFrmProductType = new FrmProductType();
                    oFrmProductType.EvtSaved += (sen, ea) =>
                    {
                        int.TryParse(sen.ToString(), out iProductTypeId);
                    };
                    oFrmProductType.Activated += (senl, eal) =>
                    {
                        oFrmProductType.ProductTypeName = cbbProductType.Text;
                    };
                    oFrmProductType.IsDialog = true;
                    oFrmProductType.ShowDialog();
                    if (iProductTypeId != default(int))
                    {
                        CreateTreeview();
                        OnReloadLstProductType();
                        cbbProductType.SelectedValue = iProductTypeId;
                    }
                }
            }
        }
        #endregion Dotnet Methods
    }
}
